# -*- coding: utf-8 -*-
"""
Created on Sun Dec 19 19:41:47 2021

@author: wulong
"""
import numpy as np
from casadi import *
from Slow_model import* 

# In[1] Slow MPC
def formulate_opt_s(initial_state, state_guess, state_bnds_lo, state_bnds_up, 
                    medium_state_guess, medium_state_bnds_lo, medium_state_bnds_up, 
                    fast_state_guess, fast_state_bnds_lo, fast_state_bnds_up, 
                    fast_state_slack_lo, fast_state_slack_up, 
                    input_guess, input_bnds_lo, input_bnds_up, 
                    medium_input_guess, medium_input_bnds_lo, medium_input_bnds_up, 
                    fast_input_guess, fast_input_bnds_lo, fast_input_bnds_up, 
                    input_bin_bnds,
                    distb_bnds,
                    output_guess, 
                    yspe_guess, yspe_bnds_lo, yspe_bnds_up,
                    output_setpnts, long_state_setpnts,  
                    alpha, alpha_slack, pred_horzn):
    w = []
    w0 = []
    lbw = []
    ubw = []
    J = 0
    g = []
    lbg = []
    ubg = []
    
    # "Lift" initial states conditions    
    xname = 'X' + str(0)
    Xk = MX.sym(xname, Nx_s)
    w += [Xk]
    lbw += [initial_state]
    ubw += [initial_state]
    w0 += [initial_state]
    
    for k in range(1, pred_horzn+1):
        # Define binary for inputs
        Zu_s = vertcat(input_bin_bnds[1], input_bin_bnds[2], 1)
        Zu_m = input_bin_bnds[1]
        Zu_f = vertcat(input_bin_bnds[0], input_bin_bnds[2])
        
        # Create input variables
        uname = 'U' + str(k-1)
        Uk = MX.sym(uname, Nuc_s)
        w += [Uk]
        lbw +=[Zu_s*input_bnds_lo]
        ubw +=[Zu_s*input_bnds_up]
        w0 += [input_guess]
        
        umname = 'U_m' + str(k-1)
        Umk = MX.sym(umname, Nuc_m)
        w += [Umk]
        lbw +=[Zu_m*medium_input_bnds_lo]
        ubw +=[Zu_m*medium_input_bnds_up]
        w0 += [medium_input_guess]
        
        ufname = 'U_f' + str(k-1)
        Ufk = MX.sym(ufname, Nuc_f)
        w += [Ufk]
        lbw +=[Zu_f*fast_input_bnds_lo]
        ubw +=[Zu_f*fast_input_bnds_up]
        w0 += [fast_input_guess]
        
        # Create medium and fast states variables
        xmname = 'X_m' + str(k)
        Xmk = MX.sym(xmname, Nx_m)
        w += [Xmk]
        lbw += [medium_state_bnds_lo]
        ubw += [medium_state_bnds_up]
        w0 += [medium_state_guess]
        
        xfname = 'X_f' + str(k)
        Xfk = MX.sym(xfname, Nx_f)
        w += [Xfk]
        lbw += [fast_state_bnds_lo]
        ubw += [fast_state_bnds_up]
        w0 += [fast_state_guess]
        
        # Create disturbance
        Dk = distb_bnds[k-1,:]
        
        # Simulate the model
        Ik = I_ode_s(x0 = Xk, p = vertcat(Xmk, Xfk, Uk, Umk, Ufk, input_bin_bnds, Dk))
        X_int = Ik['xf']
        
        # Create new states variables
        xname = 'X' + str(k)
        Xk = MX.sym(xname, Nx_s)
        w += [Xk]
        lbw += [state_bnds_lo]
        ubw += [state_bnds_up]
        w0 += [state_guess]
        
        # Add dynamic constraints
        g += [X_int - Xk]
        lbg += [[0]*Nx_s]
        ubg += [[0]*Nx_s]
        
        g += [const_ies_s(Xk, Xmk, Xfk, Uk, Umk, Ufk, input_bin_bnds, Dk)]
        lbg += [[0]*(Nx_m + Nx_f)]
        ubg += [[0]*(Nx_m + Nx_f)]
        
        # Create outputs variables
        yname = 'y' + str(k)
        Yk = MX.sym(yname, Ny_s)
        w += [Yk]
        lbw += [[-np.inf]*Ny_s]
        ubw += [[np.inf]*Ny_s]
        w0 += [output_guess]
        
        # Add output constraints
        g += [Yk - out_ies_s(Xk, Xmk, Xfk, Uk, Umk, Ufk, input_bin_bnds, Dk)]
        lbg += [[0]*Ny_s]
        ubg += [[0]*Ny_s]
        
        # Create outputs zone variables
        yname_spe = 'y_spe' + str(k)
        Yk_spe = MX.sym(yname_spe, 1) 
        w += [Yk_spe]
        lbw += [yspe_bnds_lo[k-1]] 
        ubw += [yspe_bnds_up[k-1]]
        w0 += [yspe_guess]
        
        # Add slack variables for fast states
        ename = 'e' + str(k)
        ek = MX.sym(ename, 4)
        w += [ek]
        lbw += [[0]*4] 
        ubw += [[np.inf]*4]
        w0 += [[0]*4]
        
        Xfk_slack = vertcat(Xfk[7], Xfk[8])
        ek_lo = vertcat(ek[0], ek[2])
        ek_up = vertcat(ek[1], ek[3])
        g += [Xfk_slack + ek_lo - ek_up]
        lbg += [fast_state_slack_lo]
        ubg += [fast_state_slack_up]
        
        # The cost function
        J += alpha[0] * (Yk[0] - output_setpnts[k-1])**2
        J += alpha[1] * (Yk[1] - Yk_spe)**2
        J += alpha[2] * (Ufk[0] + Umk)
        J += alpha[3] * (Xk[0] - long_state_setpnts[k-1,0])**2
        J += alpha[4] * (Xk[1] - long_state_setpnts[k-1,1])**2
        J += mtimes(mtimes(ek.T, alpha_slack), ek)
        
        pass
    
    # Concatenate decision variables and constraint terms
    w = vertcat(*w)
    lbw = vertcat(*lbw)
    ubw = vertcat(*ubw)
    w0 = vertcat(*w0)
    g = vertcat(*g)
    lbg = vertcat(*lbg)
    ubg = vertcat(*ubg)
    
    return w, lbw, ubw, w0, g, lbg, ubg, J

# In[2] Creat Slow MPC solver
def solve_opt_s(w, lbw, ubw, w0, g, lbg, ubg, J):
    print('Creat an S-MPC solver')
    nlp_prob = {'f': J, 'x': w, 'g': g}
    nlp_solver = nlpsol('nlp_solver', 'ipopt', nlp_prob)
    # Solve NLP
    print('Solve S-MPC')
    # nlp_solver.stats()
    sol = nlp_solver(x0=w0, lbx=lbw, ubx=ubw, lbg=lbg, ubg=ubg)
    print(nlp_solver.stats())
    optimalValues = sol['x'].full().ravel()
    
    return optimalValues